package site.tuluan.sp4j.module.sys.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import site.tuluan.sp4j.common.core.controller.BaseController;
import site.tuluan.sp4j.common.core.domain.AjaxResult;
import site.tuluan.sp4j.common.exception.BizException;
import site.tuluan.sp4j.common.utils.StringUtils;
import site.tuluan.sp4j.module.sys.domain.vo.LoginBody;
import site.tuluan.sp4j.module.sys.service.ISysLoginService;

import javax.annotation.Resource;

/**
 * 登录
 *
 * @author tuluan
 */
@RestController
public class SysLoginController extends BaseController {
    @Resource
    private ISysLoginService loginService;

    /**
     * 用户登录
     * @param loginBody 参数体
     * @return token
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        if (loginBody == null || StringUtils.isAnyEmpty(loginBody.getUserName(), loginBody.getPassword())) {
            return AjaxResult.buildFailureResult(AjaxResult.CODE_FAILURE, "用户名密码不能为空");
        }

        try {
            String token = loginService.login(loginBody.getUserName(), loginBody.getPassword());
            return AjaxResult.buildSuccessResult(token);
        } catch (BizException e) {
            return AjaxResult.buildFailureResult(AjaxResult.CODE_FAILURE, e.getMessage());
        }
    }

    /**
     * 退出登录
     * @return token
     */
    @PostMapping("/logout")
    public AjaxResult logout() {
        return loginService.logout() ? AjaxResult.buildSuccessResult() : AjaxResult.buildFailureResult();
    }
}
